package org.smile.tomcat.session.redis;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.catalina.Manager;

public class RedisContrastSession extends RedisSession{
	/***
	 * 缓存属性的值用来对比
	 */
	private Map<String,byte[]> cachedAttrubite=new HashMap<String,byte[]>();
	
	public RedisContrastSession(Manager manager) {
		super(manager);
	}
	
	@Override
	public Object getAttribute(String name) {
		Object value= super.getAttribute(name);
		if(value==null){
			value= store.getAttrubite(this, name);
			if(value!=null){
				super.setAttribute(name, value);
			}
		}
		return value;
	}

	@Override
	protected void onAttrubiteStoreChange(String name, byte[] datas) {
		if(datas==null){
			cachedAttrubite.remove(name);
		}else{
			cachedAttrubite.put(name, datas);
		}
	}

	@Override
	protected void afterRequest() {
		for(Map.Entry<String, byte[]> entry:this.cachedAttrubite.entrySet()){
			Object value=super.getAttribute(entry.getKey());
			byte[] valueBytes=store.serializer.serialize(value);
			if(!Arrays.equals(valueBytes,entry.getValue())){
				this.store.storeBytes(this, entry.getKey(), valueBytes);
			}
		}
	}
	
}
